<template>
  <div>
    <header class="mui-bar mui-bar-nav">
      <h1 class="mui-title">{{item.roomName}}</h1>
      <router-link to="/WelcomeDraw" replace class="mui-btn mui-btn-link mui-pull-right">返回</router-link>
    </header>
    <div class="mui-content">
      <div class="draw">
        <canvas id="canvas" class="draw-context" width="1000" height="500" :style="{'backgroundColor':backGroundColor}"
          @touchend.prevent="endDraw"
          @touchmove.prevent="moveDraw"
          @touchstart.prevent="startDraw"
          @mousedown.prevent="startDraw"></canvas>
        <div class="draw-tool">
          <div class="draw-color">
            <span v-for="(color,index)  in colors" :key="index" 
              :style="{backgroundColor:color,color:color}" 
              :class="['mui-badge',{'black':color == strokeColor && !clearRect}]"
              @click="changeStroke(color)">1</span>
          </div>
          <div class="draw-size">
            <div v-for="size in sizes" :key="size" 
             class="draw-size-body"
             @click="changeSize(size)">
              <div :class="['draw-circle',{'select': size == strokeSize }]" 
              :style="{width:size + 'px',height: size+'px','margin-top':(18-size)/2+'px'}"></div>
            </div>
          </div>
          <div class="eraser">
            <button type="button" :class="['mui-btn',{select:clearRect}]" @click="toggleEraser">橡皮擦</button>
          </div>
        </div>
      </div>  
      
    </div>
    <div class="remarkText" :style="{'height':remarkHeight+'px'}">
      <p v-for="(line,lineIndex) in reverseLines" :key="lineIndex">
          {{drawPersonInfo(line)}}
      </p>
      
    </div>
  </div>
</template>


<script>
import { mapGetters } from "vuex";
var canvas = null;
var ctx = null;

export default {
  name: "DrawRoom",
  data() {
    return {
      colors: ["red", "green", "blue", "yellow"],
      sizes: [20, 12, 6, 2],
      strokeColor: "red",
      strokeSize: 6,
      remarkHeight: 120,
      clearRect: false,
      drawObj: null,
      //allLines: [],
      backGroundColor: "#ccc"
    };
  },
  created() {
    var drawInfo = this.$store.getters.drawInfo;
    //debugger;
    if (!drawInfo || drawInfo.key == undefined) {
      this.$router.replace("WelcomeDraw");
      return;
    }
    this.$store.dispatch("getRoomInfo", drawInfo.key).then(rst => {
      if (rst.code) {
        console.log(rst.data);
      } else {
        console.log(rst.data);
        this.$router.replace("WelcomeDraw");
      }
    });
  },
  computed: mapGetters({
    drawInfo: "drawInfo"
  }),
  mounted() {
    this.$nextTick(function() {
      var windowHeight = window.innerHeight;
      var appHeight = document.getElementById("app").offsetHeight;
      this.remarkHeight = windowHeight - appHeight - 10;
      canvas = document.getElementById("canvas");
      ctx = canvas.getContext("2d");
      this.update();
    });
  },
  computed: {
    item() {
      return this.$store.getters.drawInfo;
    },
    reverseLines() {
      var arr = [];
      var allLines = this.item.drawInfoList;

      for (let i = 0; i < allLines.length; i++) {
        const item = allLines[i];
        arr.unshift(item);
      }
      return arr;
    }
  },
  methods: {
    changeStroke(color) {
      this.strokeColor = color;
      this.clearRect = false;
    },
    changeSize(size) {
      this.strokeSize = size;
    },
    toggleEraser() {
      this.clearRect = !this.clearRect;
    },
    drawPersonInfo(drawInfo) {
      if (drawInfo == null) return null;
      if (drawInfo.clearRect) {
        return `${drawInfo.userName ||
          "游客"} 为画布进行了修饰,图案看起来更漂亮了.`;
      } else {
        return `${drawInfo.userName ||
          "游客"} 为画布增添了一笔,图案看起来更丰富了.`;
      }
    },
    startDraw(evt) {
      var arr = this.getDrawXY(evt);
      this.drawObj = {
        color: this.strokeColor,
        size: this.strokeSize,
        clearRect: this.clearRect,
        userName: null,
        list: [arr]
      };
      canvas.addEventListener("mousemove", this.moveDraw, false);
      canvas.addEventListener("mouseup", this.endDraw, false);
      this.update();
    },
    moveDraw(evt) {
      var arr = this.getDrawXY(evt);
      this.drawObj.list.push(arr);
      this.update();
    },
    endDraw(evt) {
      canvas.removeEventListener("mousemove", this.moveDraw);
      canvas.removeEventListener("mouseup", this.endDraw);
      //this.allLines.push(this.drawObj);

      //提交服务器.TODO
      this.$store.dispatch("addDrawInfo", this.drawObj).then(t => {
        console.log("提交到服务器了");
        this.drawObj = null;
        this.update();
      });
    },
    update() {
      var allLines = this.item.drawInfoList;
      this.clearCanvas();
      for (const draw of allLines) {
        this.drawLine(draw);
      }
      this.drawLine(this.drawObj);
    },
    clearCanvas() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    },
    drawLine(drawObj) {
      if (drawObj == null) return;
      var arr = drawObj.list;
      ctx.save();
      ctx.lineWidth = drawObj.size;
      ctx.lineCap = "round";
      ctx.strokeStyle = drawObj.color;
      if (drawObj.clearRect) {
        ctx.globalCompositeOperation = "destination-out";
        //ctx.strokeStyle = this.backGroundColor;
      }
      ctx.beginPath();
      ctx.moveTo(arr[0][0], arr[0][1]);
      for (let s = 1; s < arr.length; s++) {
        const point = arr[s];
        ctx.lineTo(point[0], point[1]);
      }
      ctx.stroke();
      ctx.restore();
    },
    getDrawXY(e) {
      var pageX = e.pageX || e.targetTouches[0].clientX;
      var pageY = e.pageY || e.targetTouches[0].clientY;
      var rect = this.getElementRect();
      pageX -= rect.left;
      pageY -= rect.top;

      var w = canvas.width;
      var h = canvas.height;

      pageX /= (rect.right - rect.left) / w;
      pageY /= (rect.bottom - rect.top) / h;

      return [pageX, pageY];
    },
    //计算canvas在浏览器上绝对位置(from createjs)
    getElementRect() {
      var bounds;
      var e = canvas;
      try {
        bounds = e.getBoundingClientRect();
      } catch (err) {
        // this can fail on disconnected DOM elements in IE9
        bounds = {
          top: e.offsetTop,
          left: e.offsetLeft,
          width: e.offsetWidth,
          height: e.offsetHeight
        };
      }

      var offX =
        (window.pageXOffset || document.scrollLeft || 0) -
        (document.clientLeft || document.body.clientLeft || 0);
      var offY =
        (window.pageYOffset || document.scrollTop || 0) -
        (document.clientTop || document.body.clientTop || 0);

      var styles = window.getComputedStyle
        ? getComputedStyle(e, null)
        : e.currentStyle; // IE <9 compatibility.

      var padL =
        parseInt(styles.paddingLeft) + parseInt(styles.borderLeftWidth);
      var padT = parseInt(styles.paddingTop) + parseInt(styles.borderTopWidth);
      var padR =
        parseInt(styles.paddingRight) + parseInt(styles.borderRightWidth);
      var padB =
        parseInt(styles.paddingBottom) + parseInt(styles.borderBottomWidth);

      // note: in some browsers bounds properties are read only.
      return {
        left: bounds.left + offX + padL,
        right: bounds.right + offX - padR,
        top: bounds.top + offY + padT,
        bottom: bounds.bottom + offY - padB
      };
    }
  }
};
</script>

<style lang="scss" scoped>
$marginLeft: 5%;
$contentWidth: 90%;
$toolHeight: 25px;
$toolPadding: 15px;
.draw {
  width: 100%;

  .draw-context {
    margin-top: 20px;
    margin-left: $marginLeft;
    width: $contentWidth;
    height: 50vw;
  }

  .draw-tool {
    margin-left: $marginLeft;
    width: $contentWidth;
    background-color: #ddd;
    position: relative;
    .draw-color {
      height: $toolHeight;
      span {
        margin-right: $toolPadding;
        border: 1px solid #fff;
      }
      .black {
        border: 2px solid #000;
      }
    }

    .draw-size {
      margin-top: 10px;
      height: $toolHeight;
      .draw-size-body {
        float: left;
        margin-right: 11px;
        width: $toolHeight;
        height: $toolHeight;
        .draw-circle {
          background-color: #888;
          margin: auto auto;
          border-radius: 100%;
        }
        .select {
          background-color: red;
          border: 1px solid red;
        }
      }
    }
    .eraser {
      position: absolute;
      top: 5px;
      right: 10px;
      .select {
        border-color: red;
      }
    }
  }
}
.remarkText {
  position: absolute;
  bottom: 0;
  left: 5px;
  right: 5px;
  overflow: auto;
  border: 1px solid #ccc;
}
</style>
